#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

// 01-socket 192.168.100.128 8000
// argv[0]   arv[1]          argv[2]
int main(int argc, char const *argv[])
{

    int sockfd, ret;
    struct sockaddr_in server_addr;
    socklen_t addrlen;

    if (argc != 3)
    {
        fprintf(stderr, "错误:运行程序时请带入参数(./03-tcp_client ip port)\n");
        exit(-1);
    }

    // 创建一个socket
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        perror("socket");
        exit(-1);
    }

    printf("sockfd=%d\n", sockfd);

    memset(&server_addr, 0, sizeof(server_addr));     // 清空结构体
    server_addr.sin_family = AF_INET;                 // 什么类型的通信
    server_addr.sin_port = htons(atoi(argv[2]));      // 设置socket 的固定端口
    server_addr.sin_addr.s_addr = inet_addr(argv[1]); // 把字符串ip转换成网络二进制的ip地址

    ret = connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    if (ret < 0)
    {
        perror("connect");
        exit(-1);
    }

    printf("server connected\n");

    close(sockfd);

    return 0;
}
